﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Xml;

namespace YGWebMobileApi.Data
{
    /// <summary>
    /// 通信的 Json 格式转化器
    /// </summary>
    public class MobileJsonConverter
    {
        /// <summary>
        /// 将 MobileXml 对象转化为 Json
        /// </summary>
        /// <param name="mx"></param>
        /// <returns></returns>
        public static string ToJosn(MobileXml mx)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(mx.ToXml());
            return ToJosn(doc);
        }

        /// <summary>
        /// 将 MobileXml 对象转化为 Json
        /// </summary>
        /// <param name="mx"></param>
        /// <returns></returns>
        public static string ToJosn(XmlDocument doc)
        {
            // 将 Xml 转化为 json 字符串
            string json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);
            if (json == null)
            {
                throw new Exception("xml 格式有误，无法序列化为 json");
            }
            return JObject.Parse(json)[MobileXml.RootNodeName].ToString();
        }

        /// <summary>
        /// 将 Json 字符串转化为 MobileXml 对象
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static MobileXml ToXml(string json)
        {
            XmlDocument doc = JsonConvert.DeserializeXmlNode("{" + MobileXml.RootNodeName + " : " + json + "}");
            if (doc == null)
            {
                throw new Exception("json 格式有误，无法反序列化为 xml");
            }
            return new MobileXml(doc.OuterXml);
        }
    }
}